package com.wzl.thread.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

/**
 * 可缓存的无界线程池
 *
 * 当线程池中的线程空闲时间超过60s则会自动回收该线程，核心线程数为0
 * 当任务超过线程池的线程数则创建新线程。线程池的大小上限为Integer.MAX_VALUE，
 * 可看做是无限大。
 *
 * @author weizhongli
 * @since 2022-09-19 09:59
 */
@Slf4j
public class TcNewCachedThreadPool {

    /**
     * newCachedThreadPool方法  不指定线程工厂
     */
    public static Future<?> NoFactoryPool() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        //2.提交任务
//        for (int i = 0; i < 10; i++) {
//            executorService.submit(new Runnable() {
//                @Override
//                public void run() {
//
//                }
//            });
//        }
        Future<?> submit = null;
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            submit = executorService.submit(() -> {
                log.info("线程执行啦.......哈哈哈哈哈哈" + finalI);
            });
        }
        return submit;
    }

    /**
     * newCachedThreadPool(ThreadFactory threadFactory)方法
     */
    public static void factoryPool(){
        //1.使用工厂类获取线程池对象
        ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
            int n = 1;
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"自定义的线程名称" + n++);
            }
        });
        //2.提交任务
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            executorService.submit( () ->{
                log.info("线程执行啦...哈哈哈哈哈哈----" + finalI + "----" + Thread.currentThread().getName());
            });
        }

    }


}